package com.junyi;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.junyi.proto.StudentProto;

import java.util.List;

/**
 * @time: 2021年11月26日 10:40
 * @author: junyi Xu
 */
public class Main {
    public static void main(String[] args) {

        StudentProto.Student student = init();
        byte[] stuByte = student.toByteArray();
        System.out.println("protobuf数据大小: " + stuByte.length);

        // 尝试根据字节数据解析为对象
        StudentProto.Student studentParse = null;
        try {
            studentParse = StudentProto.Student.parseFrom(stuByte);
            //这里得到了Student实例了，就可以根据需要来操作里面的数据了
            System.out.println("学生ID:" + studentParse.getId());
            System.out.println("姓名：" + studentParse.getName());
            System.out.println("性别：" + (studentParse.getSex().getNumber() == 0 ? "男" : "女"));
            System.out.println("邮箱：" + studentParse.getEmail());
            //遍历phoneNumber字段
            List<StudentProto.Student.PhoneNumber> phList = studentParse.getPhoneList();
            for (StudentProto.Student.PhoneNumber p : phList) {
                System.out.println(p.getType() + "电话:" + p.getNumber());
            }
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }

        /*快速的进行json格式化*/
        String jsonObject = "";
        try {
            jsonObject = JsonFormat.printer().print(student);
        } catch (InvalidProtocolBufferException e) {
            e.getMessage();
        }

        System.out.println("json 数据：" + jsonObject);
        System.out.println("json数据大小: " + jsonObject.getBytes().length);
    }


    private static StudentProto.Student init() {
        //获取Student对象的构建器
        StudentProto.Student.Builder builder = StudentProto.Student.newBuilder();
        builder.setId(1);
        builder.setName("peter");
        builder.setEmail("123456@qq.com");
        builder.setSex(StudentProto.Student.Sex.WOMAN);

        // 制造2个PhoneNumber对象
        StudentProto.Student.PhoneNumber phoneNumber = StudentProto.Student.PhoneNumber.newBuilder().setNumber("135XX").setType(StudentProto.Student.PhoneType.MOBILE).build();
        StudentProto.Student.PhoneNumber phoneNumber2 = StudentProto.Student.PhoneNumber.newBuilder().setNumber("134XX").setType(StudentProto.Student.PhoneType.HOME).build();
        builder.addPhone(phoneNumber);
        builder.addPhone(phoneNumber2);

        return builder.build();
    }
}
